package ch.justdoit.andriodrpncalc.view;
import java.util.Stack;

import android.content.Context;
import android.graphics.Rect;
import android.text.Layout.Alignment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

public class PromptText extends EditText {


	private Stack<String> mTokenList;
	private int mTokenCursor = 0;
	

	public PromptText(Context context) {
		super(context);
		//this.setTextSize(15);
		//this.setPadding(0, 0, 0, 0);
		
		

		mTokenList = new Stack<String>();
	}

	public void addToken (String token) {
		mTokenList.add(mTokenCursor, token);
		mTokenCursor++;
		setText(text());
		setSelection(textLength(mTokenCursor));

	}
	
	public void removeToken () {
		if (mTokenCursor > 0) {
			//String token = text.get(tokenCursorPosition);
			mTokenList.remove(--mTokenCursor);
		}
		setText(text());
		setSelection(textLength(mTokenCursor));
		
	}
	
	private int textLength(int i) {
		int result = 0;
		while (i > 0) {
			i--;
			result += mTokenList.get(i).length();
		}
		
		return result;
	}

	private String text() {
		StringBuffer result = new StringBuffer("");
		for (int i = 0; i < mTokenList.size(); i++) {
			result.append(mTokenList.get(i));
		}
		return result.toString();
	}

	public void moveTokenCursor (int i) {

		if (isFocused()) {
			if (i == KeyEvent.KEYCODE_DPAD_RIGHT) {
				// move right
				if (mTokenCursor < mTokenList.size()) {
					mTokenCursor++;
				}
			} else if (i == KeyEvent.KEYCODE_DPAD_LEFT) {
				// move left
				if (mTokenCursor > 0) {
					mTokenCursor--;
				}
			}
		}
		setSelection(textLength(mTokenCursor));


	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			moveTokenCursor (KeyEvent.KEYCODE_DPAD_LEFT);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			moveTokenCursor (KeyEvent.KEYCODE_DPAD_RIGHT);
		} else if (keyCode == KeyEvent.KEYCODE_DEL) {
			removeToken();
		} 
		
		
		return false;
	}

	@Override
	protected void onFocusChanged(boolean focused, int direction, Rect rectangle) {
		if (hasFocus()){
			setSelection(textLength(mTokenCursor));
		}
	}
	
	
	public void resetText() {
		mTokenList = new Stack<String>();
		mTokenCursor = 0;
		setText(text());
		setSelection(textLength(mTokenCursor));

	}
	
	public void setTokens(Stack<String> tokenList) {
		mTokenList = tokenList;
		mTokenCursor = mTokenList.size();
		setText(text());
		setSelection(textLength(mTokenCursor));
	}
	
	public Stack<String> getTokens() {
		return mTokenList;
	}
	
	
	public boolean isEmpty() {
		if (mTokenCursor == 0) {
			return true;
		}
		else {
			return false;
		}
	}

}
